<template>
  <div class="contain-width">
    <el-backtop/>
    <h1 class="fzls-title">游戏大厅</h1>
    <el-button icon="el-icon-refresh" @click="refresh">刷新</el-button>
    <el-button icon="el-icon-circle-plus-outline" @click="setVisible=true">创建</el-button>
    <el-dialog customClass="customDia" title="房间设置" :visible.sync="setVisible">
      <Setting @onSubmit="create" @onCancel="setVisible=false" class="sets"/>
    </el-dialog>
    <el-table :data="roomList" class="table-body" stripe highlight-current-row border>
      <el-table-column prop="id" label="房间号" sortable/>
      <el-table-column label="游戏状态" :filters="filterList" :filter-method="filter" filter-placement="bottom-end">
        <template slot-scope="scope">
          <span :class="`color-${stateMap[scope.row.state].color}`">{{ scope.row.state + '中...' }}</span>
        </template>
      </el-table-column>
      <el-table-column v-for="item in playerList" :label="item.label" :key="item.label">
        <template slot-scope="scope" v-if="scope.row[item.str]">
          <el-popover trigger="hover" placement="left">
            <p>等级: {{ scope.row[item.str].level }}</p>
            <p>胜率: {{ scope.row[item.str].rate }}</p>
            <div slot="reference">{{ scope.row[item.str].name }}</div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="备注">
        <template slot-scope="scope" v-if="scope.row.remarks">
          {{ scope.row.remarks }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary" plain
            :icon="stateMap[scope.row.state].icon"
            :disabled="stateMap[scope.row.state].disabled"
            @click="stateMap[scope.row.state].click(scope.row.id, scope.row.pass)"
          >加入房间</el-button>
        </template>
      </el-table-column>
      <template slot="empty">
        <span>暂无数据</span>
        <el-link type="primary" @click="setVisible=true">点我创建一个房间</el-link>
      </template>
    </el-table>
  </div>
</template>

<script>
import Setting from '@/components/Setting.vue';
import {getAllGame, createRoom, enterRoom} from '@/api/index.js';
export default {
  components: {Setting},
  data() {
    return {
      roomList: [],
      filterList: [
        {text: '游戏中...', value: '游戏'},
        {text: '等待中...', value: '等待'},
        {text: '空闲中...', value: '空闲'}
      ],
      stateMap: {
        '游戏': {color: 'red', icon: 'el-icon-loading', disabled: true, click: () => {}},
        '等待': {color: 'yellow', icon: 'el-icon-timer', disabled: true, click: () => {}},
        '空闲': {color: 'green', icon: 'el-icon-thumb', disabled: false, click: (id, pass) => this.check(id, pass)}
      },
      playerList: [
        {label: '座位一', str: 'player0'},
        {label: '座位二', str: 'player1'}
      ],
      setVisible: false
    };
  },
  methods: {
    filter(value, row) {
      return row.state === value;
    },
    refresh() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      getAllGame().then(res => {
        this.roomList = res.data.map(item => ({
          id: item.roomId,
          isPlay: Boolean(item.state),
          player0: item.a ? {name: item.a.name, level: item.a.level, rate: item.a.win} : null,
          player1: item.b ? {name: item.b.name, level: item.b.level, rate: item.b.win} : null,
          pass: item.pass,
          remarks: item.remarks,
          state: this.isPlay ? '游戏' : (this.player0 && this.player1) ? '等待' : '空闲'
        }));
      }).catch(() => {
        this.$message.error('很遗憾 获取房间列表失败');
      }).finally(() => {
        loading.close();
      });
    },
    createSend(form) {
      createRoom({
        rule: [form.side, form.edition, form.time, form.robot].join('~'),
        playerAId: form.side === 0 ? this.$cookies.get('user').id : '',
        playerBId: form.side !== 0 ? this.$cookies.get('user').id : '',
        pass: form.pass || '',
        desc: form.desc || ''
      }).then(res => {
        if (res.data.succeed) {
          form.roomId = res.data.roomId; // 根据服务器的返回值拿到roomId
          this.$cookies.set('room', form, '1d'); // 存储roomId到cookies
          this.$socket.emit('enter', {roomId: res.data.roomId}); // 进入socket房间
          this.$router.push({name: 'game'});
        }
        else {
          this.$message.error('很遗憾 创建房间失败');
        }
      }).catch(() => {
        this.$message.error('很遗憾 创建房间失败');
      });
    },
    create(form) {
      if (this.$cookies.isKey('room')) {
        this.$confirm('检测到您已经加入其他对局，是否退出原来的房间？', '提示', {
          confirmButtonText: '退出并新建房间',
          cancelButtonText: '取消并返回房间',
          type: 'warning'
        }).then(() => {
          this.createSend(form);
        }).catch(() => {
          this.$message({type: 'info', message: '取消新建，返回原房间'});
          this.$router.push({name: 'game'});
        });
      }
      else {
        this.createSend(form);
      }
    },
    enter(roomId, pass) {
      let calculateSide = -1;
      for (let itRoom of this.roomList) {
        if (itRoom.id === roomId) {
          if (itRoom.player0) {
            calculateSide = 1;
          }
          else if (itRoom.player1) {
            calculateSide = 0;
          }
          break;
        }
      }
      enterRoom({
        roomId,
        playerId: this.$cookies.get('user').id,
        pwd: pass
      }).then(res => {
        const rule = res.data.rule.split('~');
        const form = {
          roomId: +roomId,
          side: calculateSide, // 虽然改过了但还是有BUG
          edition: +rule[1],
          time: rule[2],
          robot: (rule[3] !== 'false')
        };
        this.$cookies.remove('room');
        this.$cookies.set('room', form, '1d'); // 根据roomId拿到form，再对cookies进行set
        this.$socket.emit('enter', {roomId});
        this.$router.push({name: 'game'});
      }).catch(() => {
        this.$message({message: '很遗憾 进入房间失败', type: 'warning'});
      });
    },
    checkPass(roomId, pass) {
      if (!pass) {
        this.enter(roomId, pass);
      }
      else {
        this.$prompt('请输入密码', '进入房间', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({value}) => {
          value === pass ? this.enter(roomId, pass) : this.$message.error('密码错误');
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '房间进入失败'
          });
        });
      }
    },
    check(roomId, pass) { // 先检查是否加入其他房间
      if (this.$cookies.isKey('room')) {
        this.$confirm('检测到您已经加入其他对局，是否退出原来的房间？', '提示', {
          confirmButtonText: '退出并加入新房间',
          cancelButtonText: '取消并返回原房间',
          type: 'warning'
        }).then(() => {
          const user = this.$cookies.get('user');
          this.$socket.emit('leave', {roomId: this.$cookies.get('room').roomId});
          this.$cookies.remove('room'); // 这里出现过删除room后cookie为空的BUG
          this.$cookies.set('user', {...user, ready: false});
          this.checkPass(roomId, pass); // 再进行密码检查
        }).catch(() => {
          this.$message({type: 'info', message: '已取消，返回原房间'});
          this.$router.push({name: 'game'});
        });
      }
      else {
        this.checkPass(roomId, pass); // 再进行密码检查
      }
    }
  },
  created() {
    if (this.$cookies.isKey('user')) {
      this.refresh();
    }
    else {
      this.$notify({title: '注意', message: '您还没有登录，无法加入房间'});
      this.$router.push({name: 'login'});
    }
  }
};
</script>

<style scoped>
.contain-width {
  width: 80%;
  margin-left: 8%;
}
.table-body {
  width: 100%;
  margin-top: 2em;
}
</style>
